using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Comteck.Dto.Orders;
using Comteck.Ktt.Services.Orders;
using Comteck.Localization;
using Comteck.Winforms;
using Comteck.Winforms.Forms;
using Comteck.Winforms.Infrastructure;
using DevExpress.XtraBars;
using ExpressMapper.Extensions;

namespace Comteck.Ktt.WinUI.Orders {
  /// <summary>
  /// 
  /// </summary>
  public partial class FrmSelfOrgAction : FrmEditBase {
    private readonly ISelfOrgService selfOrgService;
    private SelfOrgDto bindModel = new SelfOrgDto();

    public FrmSelfOrgAction(ISelfOrgService selfOrgService) {
      this.selfOrgService = selfOrgService;
      InitializeComponent();
    }

    private async void FrmSelfOrgAction_Load(object sender, EventArgs e) {
      if (this.DesignMode) {
        return;
      }

      mvvmContext1.BindForm(bindModel, dxValidationProvider1);

      await BindHelper.BindSelfOrgTag(ckTagIds);
      await this.LoadFormData();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private async Task LoadFormData() {
      ajaxLoad.Show();
      var result = await selfOrgService.GetEditModelAsync(this.EntityId.To<int>());
      ajaxLoad.Hide();
      result.MapTo(bindModel);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private async void btnSave_ItemClick(object sender, ItemClickEventArgs e) {
      if (await Save()) {
        this.DialogResult = DialogResult.Yes;
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private async Task<bool> Save() {
      if (!dxValidationProvider1.Validate()) {
        return false;
      }

      ajaxLoad.Show();
      var result = await selfOrgService.SaveAsync(bindModel);
      ajaxLoad.Hide();
      if (result.Code == 1) {
        result.Data.MapTo(bindModel);
        // 刷新主界面
        this.ShowMsg(BaseResources.Save_Success);
        this.AddOrUpdateAction?.Invoke(result.Data);
        return true;
      } else {
        this.ShowMsg(BaseResources.Save_Failed_Reason, result.Message);
        return false;
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnClose_ItemClick(object sender, ItemClickEventArgs e) {
      this.Close();
    }
  }
}
